package lew.bing.exp.alg;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.function.Function;

/**
 * Created by 刘国兵 on 2018/9/25.
 */
public class MyFuture<T> {

    private Callable<T> callable;

    public MyFuture(Callable<T> callable) {
        this.callable = callable;
    }

    // 什么时候会执行
    public void onComplete(ExecutorService pools,Try<T> trys) {
        pools.execute(() -> {
            try {
                trys.onSuccess(callable.call());
            } catch (Exception e) {
                trys.onFailure(e);
            }
        });
    }

    public void onSuccess(ExecutorService pools,DoSuccess<T> success ) {
        onComplete(pools,success);
    }

    public void onFuilure(ExecutorService pools,DoFailure<T> failure) {
        onComplete(pools,failure);
    }

    public <S> MyFuture<S> map(ExecutorService pools,Function<T,S> transfer){
        Callable<S> newCallable = () -> {
            Future<T> submit = pools.submit(callable);
            return transfer.apply(submit.get());
        };
        return new MyFuture<>(newCallable);
    }



}
